#!/usr/bin/env bash
# Auto-deploy loop for the online-booking-tool TEST SERVER folder.
# Polls GitHub every 5s; on a new commit, pulls and restarts the mock server.
# This folder is never edited by hand — it only advances via this pull loop.
set -u
cd "$(dirname "$0")"

# pm2's Windows service runs as NT AUTHORITY\SYSTEM, which doesn't own this
# folder (Administrator does) — git's "dubious ownership" protection blocks
# every command unless safe.directory is set. That's set in TWO system
# gitconfig files now (C:\Program Files\Git\etc\gitconfig and the mingw64
# copy under it) — Git for Windows ships two separate git builds (the cmd/
# wrapper and the mingw64/MSYS one bash actually resolves to) each reading
# a different "system" config path. Note: safe.directory can NOT be set via
# `git -c` — git deliberately ignores it there as an anti-bypass measure,
# so this has to be a real config file, not a per-command flag.

echo "[watch-and-deploy] whoami: $(whoami 2>&1)"
echo "[watch-and-deploy] which git: $(which git 2>&1)"
echo "[watch-and-deploy] git --version: $(git --version 2>&1)"
echo "[watch-and-deploy] git config --list --show-origin (safe only):"
git config --list --show-origin 2>&1 | grep -i safe
echo "[watch-and-deploy] watching origin/main, checking every 5s..."

while true; do
  git fetch origin main -q
  LOCAL=$(git rev-parse HEAD)
  REMOTE=$(git rev-parse origin/main)

  if [ "$LOCAL" != "$REMOTE" ]; then
    echo "[watch-and-deploy] new commit detected ($LOCAL -> $REMOTE), deploying..."
    git pull origin main -q
    (cd servicetitan-mock && npm install --silent)
    pm2 restart servicetitan-mock-test
    echo "[watch-and-deploy] deployed $REMOTE. Static files: refresh browser to see changes."
  fi

  sleep 5
done
